"""
WMS核心接口测试套件
运行四个核心接口的完整测试：
1. 样品放置接口
2. 样品移除接口  
3. 样品查找接口
4. 空位获取接口
"""
import sys
import os
import time
import requests

# 添加test目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from test_sample_place import test_sample_place
from test_sample_remove import test_sample_remove
from test_sample_location import test_sample_location
from test_available_position import test_available_position

BASE_URL = "http://127.0.0.1:58501"

def check_server_health():
    """检查服务器是否正常运行"""
    try:
        response = requests.get(f"{BASE_URL}/api/health", timeout=5)
        return response.status_code == 200
    except:
        return False

def clear_test_data():
    """清理可能残留的测试数据"""
    print("清理测试数据...")
    test_samples = [
        ("AGV1", "TEST001"), ("AGV2", "TEST001"), ("AGV1", "TEST002"), 
        ("AGV1", "TEST003"), ("AGV1", "TEST004"),
        ("AGV1", "REMOVE001"), ("AGV2", "REMOVE001"),
        ("AGV1", "LOCATE001"), ("AGV2", "LOCATE002"), ("AGV1", "TEST-001_ABC"),
        ("AGV1", "AVAILABLE_TEST001")
    ]
    
    for plate_name, sample_id in test_samples:
        try:
            requests.delete(f"{BASE_URL}/api/samples/{plate_name}/{sample_id}", timeout=3)
        except:
            pass
    
    # 清理可能的填充测试数据
    for i in range(10):
        try:
            requests.delete(f"{BASE_URL}/api/samples/AGV2/FILL_TEST_{i:03d}", timeout=3)
        except:
            pass
    
    print("测试数据清理完成")

def run_all_tests():
    """运行所有核心接口测试"""
    print("=" * 60)
    print("WMS核心接口测试套件")
    print("=" * 60)
    
    # 检查服务器状态
    print("\n检查服务器状态...")
    if not check_server_health():
        print("❌ 服务器未运行或无法访问！")
        print("请确保WMS服务已启动在 http://127.0.0.1:58501")
        return False
    else:
        print("✅ 服务器运行正常")
    
    # 清理测试数据
    clear_test_data()
    
    # 运行测试
    tests = [
        ("样品放置接口", test_sample_place),
        ("样品移除接口", test_sample_remove),
        ("样品查找接口", test_sample_location),
        ("空位获取接口", test_available_position)
    ]
    
    results = []
    
    for test_name, test_func in tests:
        print(f"\n{'='*60}")
        print(f"开始测试: {test_name}")
        print(f"{'='*60}")
        
        try:
            start_time = time.time()
            test_func()
            end_time = time.time()
            duration = end_time - start_time
            
            print(f"\n✅ {test_name} 测试完成 (耗时: {duration:.2f}秒)")
            results.append((test_name, "通过", duration))
            
        except Exception as e:
            print(f"\n❌ {test_name} 测试失败: {str(e)}")
            results.append((test_name, "失败", 0))
        
        # 测试间隔
        time.sleep(1)
    
    # 最终清理
    clear_test_data()
    
    # 输出测试结果汇总
    print(f"\n{'='*60}")
    print("测试结果汇总")
    print(f"{'='*60}")
    
    total_tests = len(results)
    passed_tests = sum(1 for _, status, _ in results if status == "通过")
    failed_tests = total_tests - passed_tests
    
    print(f"总测试数: {total_tests}")
    print(f"通过: {passed_tests}")
    print(f"失败: {failed_tests}")
    print()
    
    for test_name, status, duration in results:
        status_icon = "✅" if status == "通过" else "❌"
        if status == "通过":
            print(f"{status_icon} {test_name:<20} {status:<6} ({duration:.2f}秒)")
        else:
            print(f"{status_icon} {test_name:<20} {status}")
    
    print(f"\n{'='*60}")
    if failed_tests == 0:
        print("🎉 所有测试通过！WMS核心接口工作正常。")
    else:
        print(f"⚠️  有 {failed_tests} 个测试失败，请检查相关接口。")
    print(f"{'='*60}")
    
    return failed_tests == 0

if __name__ == "__main__":
    success = run_all_tests()
    sys.exit(0 if success else 1) 